<div class="container-fluid" id="LG">
    <div class="row-fluid">
        <div class="span12">
            <% $.et.load('template/menu.et.html', data) %>
                <div style="margin-top: 10px;" class="panel panel-default">
                    <div class="panel-body">
                        <div>
                            <button class="btn btn-primary" onclick="$('#curPath').html(R.curPath=='/'?'/':R.curPath+'/');$('#mkdir_input').val('');$('#mkdir_modal').modal('show')">新建文件夹</button>
                            <button class="btn btn-primary" onclick="$('#fileupload').click()">上传文件</button>
                            <button class="btn btn-primary" onclick="R.copyFilesClick()">复制选中项</button>
                            <button class="btn btn-primary" onclick="R.moveFilesClick()">移动选中项</button>
                            <button class="btn btn-primary" onclick="R.deleteFiles()">删除选中项</button>
                            <button class="btn btn-primary" onclick="R.compressFilesClick()">压缩选中项</button>
                        </div>
                        <div style="margin-top: 10px;" class="panel panel-default">
                            <div class="panel-heading">
                                <h2 class="panel-title">文件列表</h2>
                            </div>
                            <div class="panel-body">
                                <table class="table">
                                    <thead>
                                        <th style="width:40px;"><input type="checkbox" id="allCheck" onclick="$('.file_checkbox').prop('checked',$(this).prop('checked'))"
                                            /></th>
                                        <th style="width:auto;">文件名</th>
                                        <th style="width:100px;">类型</th>
                                        <th style="width:150px;">尺寸</th>
                                        <th style="width:100px;">日期</th>
                                    </thead>
                                    <tbody id="fileBody">
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                    <div class="panel-footer">
                        <% $.et.load('template/version.et.html', data) %>
                    </div>
                </div>
        </div>
    </div>
</div>
<input type="file" id="fileupload" style="display:none;" multiple onchange="R.uploadFiles()" />
<!-- 模态窗口 -->
<div class="modal fade" id="mkdir_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                      &times;
                </button>
                <h4 class="modal-title">
                    请输入文件夹名称
                </h4>
            </div>
            <div class="modal-body">
                <div class="input-group input-group-lg">
                    <span id="curPath" class="input-group-addon"></span>
                    <input id="mkdir_input" type="text" class="form-control" />
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="R.mkdirs()">创建
                </button>
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭
                </button>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="compress_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                      &times;
                </button>
                <h4 class="modal-title">
                    请输入压缩文件保存位置
                </h4>
            </div>
            <div class="modal-body">
                <div class="input-group input-group-lg">
                    <span id="curPath" class="input-group-addon">/</span>
                    <input id="compress_input" type="text" class="form-control" />
                </div>
                <br>
                <span style="color: red">
                        注: 软件将会把选定文件压缩成7zip格式
                        <br>
                        （例: bak/server.7z，压缩选定文件到bak目录下的server.7z文件中）
                    </span>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="R.compressFiles()">压缩
                </button>
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭
                </button>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="dirSelect_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                        &times;
                    </button>
                <h4 class="modal-title" id="dirSelect_title">
                </h4>
            </div>
            <div class="modal-body">
                <table class="table">
                    <thead>
                        <th style="width:auto;">目录名称</th>
                    </thead>
                    <tbody id="dirBody">
                    </tbody>
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="R.dirSelectCallback(R.curDirPath);" data-dismiss="modal">确定
                </button>
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭
                </button>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="code_modal" tabindex="-1" role="dialog" data-backdrop="static" aria-hidden="true">
    <div class="modal-dialog" style="width: 800px;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                      &times;
                </button>
                <h4 class="modal-title" id="code_title">
                </h4>
            </div>
            <div class="modal-body">
                <div id="editor" style="height: 400px; font-size: 16px;"></div>
            </div>
            <div class="modal-footer">
                <button type="button" onclick="R.onlineEditClick(R.filePath, R.getChangeEncoding())" class="btn btn-primary" data-dismiss="modal">切换编码
                </button>
                <button type="button" class="btn btn-primary" onclick="R.saveFileChange()">保存修改
                </button>
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭
                </button>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="file_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                      &times;
                </button>
                <h4 class="modal-title" id="myModalLabel">
                    提示
                </h4>
            </div>
            <div class="modal-body" id="file_text">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-dismiss="modal" onclick="R.renameClick()">重命名
                </button>
                <button type="button" class="btn btn-primary" data-dismiss="modal" onclick="$('#fileDownload').attr('src','core/file/download.mcs?path='+R.filePath+'&amp;token='+webmcs.getToken());">下载
                </button>
                <button type="button" id="unCompressButton" class="btn btn-primary" data-dismiss="modal" onclick="R.unCompress(R.filePath);">解压
                </button>
                <button type="button" id="onlineEditButton" class="btn btn-primary" data-dismiss="modal" onclick="R.onlineEditClick(R.filePath)">在线编辑
                </button>
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭
                </button>
            </div>
        </div>
    </div>
</div>
<iframe style="display:none;" id="fileDownload"></iframe>
<script>
    R.filePath = "";
    R.curPath = "";
    R.curDirPath = "";
    R.uploadFiles = function(){
        var formData = new FormData();
        var files = $('#fileupload')[0];
        for(var i=0;i<files.files.length;i++){
		    formData.append("file", files.files[i]);
        }
        if (i != 0){
            formData.append("path", R.curPath);
            R.showLoading('上传中');
            $.ajax({
                type : "post",
                url : "core/file/uploadFiles.mcs?token=" + webmcs.getToken(),
                dataType : "json",
                data: formData,
                processData: false,
                contentType: false,
                success: function(){
                    R.closeAll();
                    R.getFiles(R.curPath);
                },
                error: function(){
                    R.closeAll();
                }
            });
        }
    }
    R.dirSelectLoadDir = function (dir) {
        R.curDirPath = dir;
        webmcs.file.getfiles(dir, function(data){
            if (data.status){
                var html = "";
                var arr = data.dirs;
                for (var i = 0; i < arr.length; i++) {
                    if (dir == "/" && arr[i][0] == "..") {
                        continue;
                    }
                    var filename = arr[i][0] == ".." ? "返回上级" : arr[i][0];
                    html += "<tr>";
                    html += "<td><a href='javascript:;' onclick='R.dirSelectLoadDir(\"" + R.fileNameFilter(arr[i][1]) + "\")'>" + filename + "</a></td>"
                    html += "</tr>";
                }
                $("#dirBody").html(html);
            }
        });
    }
    R.getFiles = function (path) {
        R.curPath = path;
        webmcs.file.getfiles(path, function (data) {
            if (data.status) {
                var html = "";
                var arr = data.dirs;
                for (var i = 0; i < arr.length; i++) {
                    if (path == "/" && arr[i][0] == "..") {
                        continue;
                    }
                    var filename = arr[i][0] == ".." ? "返回上级" : arr[i][0];
                    if (filename == '返回上级'){
                        html += "<tr><td><input type='checkbox' disabled=disabled /></td>";
                    }else{
                        html += "<tr><td><input class='file_checkbox' type='checkbox' value='" + R.fileNameFilter(arr[i][1]) + "' /></td>";
                    }
                    html += "<td><a href='javascript:;' onclick='R.getFiles(\"" + R.fileNameFilter(arr[i][1]) + "\")'>" + filename + "</a></td><td>Dir</td><td>-</td>"
                    html += "<td>-</td></tr>";
                }
                arr = data.files;
                for (var i = 0; i < arr.length; i++) {
                    html += "<tr><td><input class='file_checkbox' type='checkbox' value='" + R.fileNameFilter(arr[i][3]) + "' /></td>";
                    html += "<td><a href='javascript:;' onclick='R.filePath=\"" + R.fileNameFilter(arr[i][3]) + "\";R.checkFile(this)'>" + arr[i][0] + "</a></td>";
                    html += "<td>File</td>";
                    html += "<td>" + R.getFileSize(arr[i][1]) + "</td>"
                    html += "<td>" + arr[i][2] + "</td>"
                }
                $('#allCheck').prop('checked', false);
                $("#fileBody").html(html);
            } else {
                if (data.msg == "NOTLOGIN") {
                    R.notLogin();
                }
            }
        });
    }
    R.mkdirs = function () {
        var dir = $("#mkdir_input").val();
        if (dir == '') {
            R.showToast("请输入目录名称！");
        } else {
            webmcs.file.mkdir(R.curPath + '/' + dir, function (data) {
                if (data.status) {
                    $('#mkdir_input').val('');
                    $('#mkdir_modal').modal('hide');
                    R.getFiles(R.curPath);
                } else {
                    switch (data.msg) {
                        case 'NOTLOGIN':
                            R.showToast('请先登录！');
                            break;
                        case 'DIREXITS':
                            R.showToast('文件已存在，请检查后重试！');
                            break;
                        case 'NAMEERROR':
                            R.showToast('文件创建失败，请检查文件夹名称是否合法！');
                            break;
                        case 'NETERROR':
                            R.showToast('网络错误，创建文件失败！');
                            break;
                    }
                }
            });
        }
    }
    R.getFileSize = function (size) {
        size = Number(size);
        if (isNaN(size))
            return "-";
        if (size > 1024 * 1024 * 1024)
            return (size / 1024 / 1024 / 1024).toFixed(2) + "GB";
        if (size > 1024 * 1024)
            return (size / 1024 / 1024).toFixed(2) + "MB";
        if (size > 1024)
            return (size / 1024).toFixed(2) + "KB";
        if (size < 1024)
            return size + "Byte";
    }
    R.renameClick = function(){
        layer.open({
            type: 1,
            content: '<input type="text" style="width: 500px;height: 40px;margin: 20px;margin-top: 0;" id="rename_input" />',
            title: '请输入新文件名',
            btn: ['保存', '取消'],
            yes: function(){
                webmcs.file.renameFile(R.filePath, $('#rename_input').val(), function(data){
                    if(data.status){
                        layer.closeAll();
                        R.getFiles(R.curPath);
                    }else if(data.msg == 'NOTLOGIN'){
                        R.showToast('您的登录状态已失效，请重新登录后重试！');
                    }else if(data.msg == 'NETERROR'){
                        R.showToast('网络异常，修改文件名失败，请重试！');
                    }else if(data.msg == 'EXCEPTION'){
                        R.showToast('修改文件名发生异常：' + data.exception);
                    }else{
                        R.showToast('发生异常：' + data.msg);
                    }
                });
            },
            success: function(){
                $('#rename_input').val(R.filePath.substring(R.filePath.lastIndexOf('/') + 1));
            }
        });
    }
    R.curEncoding = 'UTF-8';
    R.getChangeEncoding = function(){
        if (R.curEncoding == 'UTF-8'){
            return 'GBK';
        }else{
            return 'UTF-8';
        }
    }
    R.saveFileChange = function(){
        webmcs.file.putFileContent(R.filePath, R.editor.getValue() , R.curEncoding, function(data){
            if (data.status){
                $('#code_modal').modal('hide');
                R.getFiles(R.curPath);
            }else if(data.msg == 'NOTLOGIN'){
                R.showToast('登录状态已失效，请重新登录！');
            }else if(data.msg == 'NETERROR'){
                R.showToast('网络异常，保存文件失败，请重试！');
            }else if(data.msg == 'EXCEPTION'){
                R.showToast('保存时发生异常，原因是：' + data.exception);
            }else{
                R.showToast('发生未知异常，异常名称' + data.msg);
            }
        });
    }
    R.onlineEditClick = function(path, encoding){
        function getAceMode(){
            path = path.toLowerCase();
            if (path.endsWith(".yml")) return "yaml";
            if (path.endsWith(".xml")) return "xml";
            if (path.endsWith(".bat")) return "batchfile";
            if (path.endsWith(".txt")) return "text";
            if (path.endsWith(".log")) return "text";
            if (path.endsWith(".properties")) return "properties";
            if (path.endsWith(".json")) return "json";
        }
        encoding = encoding==undefined?"UTF-8":encoding;
        R.editor = ace.edit("editor");
        R.editor.setTheme("ace/theme/monokai");
        R.curEncoding = encoding;
        webmcs.file.getFileContent(path, encoding, function(data){
            R.showLoading('读取中');
            if (data.status){
                R.editor.getSession().setMode("ace/mode/" + getAceMode());
                R.editor.setValue(data.content);
                $('#code_title').html('文件[' + path + ']编辑');
                setTimeout(function(){
                    R.closeAll();
                    $('#code_modal').modal('show');
                }, 500);
            }else if(data.msg == 'NOLOGIN'){
                R.notLogin();
            }else if(data.msg == 'NETERROR'){
                R.showToast('网络异常读取文件内容失败，请稍后重试！');
            }else if(data.msg == 'EXCEPTION'){
                R.showToast('读取文件内容失败，原因是：' + data.exception);
            }else{
                R.showToast('发生未知异常，请联系作者。错误代码：' + data.msg);
            }
        });
    }
    R.checkFile = function (me) {
        function isCompressFile(fileName){
            var suffixArr = ['.zip', '.7z'];
            return suffixInArray(fileName, suffixArr);
        }
        function isTextFile(fileName){
            var suffixArr = ['.txt', '.bat','.json', '.xml', '.yml', '.log', '.properties'];
            return suffixInArray(fileName, suffixArr);
        }
        function suffixInArray(fileName, arr){
            fileName = fileName.toLowerCase();
            for (var i=0;i<arr.length;i++){
                if (fileName.endsWith(arr[i])){
                    return true;
                }
            }
            return false;
        }
        var fileName = $(me).html();
        if (isCompressFile(fileName)){
            $('#unCompressButton').show();
        }else{
            $('#unCompressButton').hide();
        }
        if (isTextFile(fileName)){
            $('#onlineEditButton').show();
        }else{
            $('#onlineEditButton').hide();
        }
        $("#file_text").html("您选择了文件\"" + $(me).html() + "\"");
        $("#file_modal").modal("show");
    }
    R.fileNameFilter = function (filename) {
        filename = filename.replace(/'/g, "\\&apos;");
        filename = filename.replace(/"/g, '\\&quot;');
        return filename;
    }
    R.compressFiles = function () {
        var saveFile = $('#compress_input').val();
        if (!saveFile) {
            R.showToast('请输入压缩文件保存位置！');
            return;
        }
        var fileNames = R.getSelectedFiles();
        R.showLoading('压缩中');
        webmcs.file.compressFiles(fileNames, saveFile, function (data) {
            R.closeAll();
            if (data.status) {
                $('#compress_modal').modal('hide');
                R.getFiles(R.curPath);
                return;
            } else if (data.msg == 'NOTLOGIN') {
                R.showToast('请先登录账号再使用这个功能！');
            } else if (data.msg == 'NETERROR') {
                R.showToast('网络异常，发送压缩请求失败！');
            } else if (data.msg == 'EXCEPTION') {
                R.showToast('后台压缩出现异常，请关闭可能导致文件占用的程序后重试！');
            } else {
                R.showToast('发生未知异常，请反馈给作者。异常名称：' + data.msg);
            }
        });
    }
    R.compressFilesClick = function () {
        var files = R.getSelectedFiles();
        if (files.length == 0) {
            R.showMsg("请至少选择一个要压缩的文件或目录！");
            return;
        }
        $('#compress_input').val('');
        $('#compress_modal').modal('show');
    }
    R.deleteFiles = function () {
        var fileNames = R.getSelectedFiles();
        if (fileNames.length == 0) {
            R.showMsg("请至少选择一个要删除的文件或目录！");
            return;
        }
        layer.open({
            content: '您确定要删除选中的' + fileNames.length + '个文件么？',
            btn: ['确定', '取消'],
            yes: function (index) {
                webmcs.file.delfiles(fileNames, function (data) {
                    if (data.status) {
                        R.getFiles(R.curPath);
                        layer.close(index);
                    } else if (data.msg == "NOTLOGIN") {
                        R.showToast("请先登录账号再进行操作！");
                    } else if (data.msg == "NETERROR") {
                        R.showToast("网络访问异常，未能删除选中文件！");
                        layer.close(index);
                    } else if (data.msg == "UNKNOWNERROR") {
                        R.showToast("删除文件出现异常，请关闭服务器等可能占用文件的程序后重试！");
                        R.getFiles(R.curPath);
                        layer.close(index);
                    } else {
                        R.showToast("未知的错误，如果重复出现请反馈给作者。错误类型：" + data.msg);
                    }
                });
            }
        });
    }
    R.moveFilesClick = function () {
        var fileNames = R.getSelectedFiles();
        if (fileNames.length === 0) {
            R.showMsg('请至少选择一个文件进行移动！');
            return;
        }
        R.openDirSelectModal('请选择移动到的位置', function (dir) {
            for(var i=0;i<fileNames.length;i++){
                if (dir.startsWith(fileNames[i])){
                    R.showMsg('不能把目录移动到自己内部！');
                    return;
                }
            }
            webmcs.file.moveFiles(fileNames, dir, function(data){
                if (data.status){
                    R.getFiles(dir);
                }else if(data.msg == 'NOTLOGIN'){
                    R.notLogin();
                }else if(data.msg == 'NETERROR'){
                    R.showMsg('网络错误，移动文件失败！');
                }else if(data.msg == 'MOVEOPYSAME'){
                    R.showMsg('移动的目标目录和当前目录相同！');
                }else if(data.msg == 'EXCEPTION'){
                    R.showMsg('移动文件发生异常，移动失败！');
                    R.getFiles(dir);
                }else{
                    R.showToast('发生未知异常，请联系作者。异常代码：' + data.msg);
                }
            });
        });
    }
    R.unCompress = function(filePath){
        R.openDirSelectModal('请选择解压到的位置', function(dir){
            R.showLoading('解压中');
            webmcs.file.unCompress(filePath, dir, function(data){
                R.closeAll();
                if (data.status){
                    R.getFiles(dir);
                }else{
                    if (data.msg == 'EXCEPTION'){
                        R.showToast('解压发生异常，原因是：' + data.exception);
                    }else if(data.msg == 'NOTLOGIN'){
                        R.notLogin();
                    }else if(data.msg == 'NETERROR'){
                        R.showToast('网络异常，发送解压请求失败！');
                    }else{
                        R.showToast('发生未知异常，请联系作者。异常代码：' + data.msg);
                    }
                }
            });
        });
    }
    R.copyFilesClick = function () {
        var fileNames = R.getSelectedFiles();
        if (fileNames.length === 0) {
            R.showMsg('请至少选择一个文件进行复制！');
            return;
        }
        R.openDirSelectModal('请选择复制到的位置', function (dir) {
            for(var i=0;i<fileNames.length;i++){
                if (dir.startsWith(fileNames[i])){
                    R.showMsg('不能把目录复制到自己内部！');
                    return;
                }
            }
            webmcs.file.copyFiles(fileNames, dir, function(data){
                if (data.status){
                    R.getFiles(dir);
                }else if(data.msg == 'NOTLOGIN'){
                    R.notLogin();
                }else if(data.msg == 'NETERROR'){
                    R.showMsg('网络错误，复制文件失败！');
                }else if(data.msg == 'COPYSAME'){
                    R.showMsg('复制的目标目录和当前目录相同！');
                }else if(data.msg == 'EXCEPTION'){
                    R.showMsg('复制文件发生异常，复制失败！');
                    R.getFiles(dir);
                }else{
                    R.showToast('发生未知异常，请联系作者。异常代码：' + data.msg);
                }
            });
        });
    }
    R.openDirSelectModal = function (title, callback) {
        R.showLoading('请稍等');
        R.dirSelectCallback = callback;
        $('#dirSelect_title').html(title);
        R.dirSelectLoadDir('/');
        setTimeout(function(){
            R.closeAll();
            $('#dirSelect_modal').modal('show');
        }, 500);
    }
    R.getSelectedFiles = function () {
        var files = $(".file_checkbox:checked");
        var fileNames = [];
        for (var i = 0; i < files.length; i++) {
            fileNames.push($(files[i]).val());
        }
        return fileNames;
    }
    R.getFiles("/");
</script>